﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using MyTime.Core.Entities;
using MyTime.ProviderFactory;
using MyTime.ProviderFactory.Entities;
using Raven.Client;

namespace MyTime.RavenDbProvider
{
    public class Service : MyTimeProviderBase
    {
        public override string Name
        {
            get { return "RavenDbProvider"; }
        }

        public override void Initialize(string name, NameValueCollection config)
        {
        }

        public override void AddTask(ITimeItem timeItem)
        {
            if (timeItem == null)
                throw new ArgumentNullException("timeItem");

            EndLastTask();
            var defaultTimeItem = timeItem as DefaultTimeItem;

            using (var session = DocumentStore.GetDocumentStore().OpenSession())
            {
                session.Store(defaultTimeItem);
                session.SaveChanges();
            }
        }

        private static void EndLastTask()
        {
            using (var session = DocumentStore.GetDocumentStore().OpenSession())
            {
                //var lastTask = session.Query<DefaultTimeItem>().OrderBy(task => task.WeekNumber).ThenBy(task => task.StartTime).LastOrDefault();
                var lastTask = session.Query<DefaultTimeItem>().OrderByDescending(task => task.Id).FirstOrDefault();
                if (lastTask == null)
                    return;
                lastTask.EndTime = DateTime.Now;
                lastTask.TotalTime = (lastTask.EndTime.Value.Subtract(lastTask.StartTime));

                session.Store(lastTask);
                session.SaveChanges();
            }
        }

        public override IEnumerable<ITimeItem> GetAllTime()
        {
            using (var session = DocumentStore.GetDocumentStore().OpenSession())
            {
                return session.Query<DefaultTimeItem>().ToList();
            }
        }

        public override IEnumerable<ITimeItem> GetTodaysTimeItems()
        {
            using (var session = DocumentStore.GetDocumentStore().OpenSession())
            {
                var todaysTasks =
                    session.Query<DefaultTimeItem>().Where(task => task.StartTime.Date == DateTime.Now.Date).ToList();
                return todaysTasks;
            }
        }

        public override bool ImportOldData(double version, params string[] param)
        {
            throw new NotImplementedException();
        }

        public override ITimeItem GetCurrentTimeItem()
        {
            using (var session = DocumentStore.GetDocumentStore().OpenSession())
            {
                var lastTasks = session.Query<DefaultTimeItem>().OrderBy(task => task.WeekNumber).ThenBy(task => task.StartTime).
                        Last();
                return lastTasks;
            }
        }
    }
}